package org.lifxue.jqda.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRootPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;

import org.lifxue.jqda.data.DataUtil;
import org.lifxue.jqda.data.bean.AppInfoBean;
import org.lifxue.jqda.run.Command;
import org.lifxue.jqda.ui.autofield.AutoCompletionField;
import org.lifxue.jqda.ui.autofield.DefaultCompletionFilter;
import org.lifxue.jqda.util.GlobalConstant;
import org.lifxue.jqda.util.GlobalVar;

/**
 * 
 * @Description:
 * @Author: zhangzuoqiang
 * @Date: Sep 26, 2011
 */
public class QuickStartJFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// private static Log logger = LogFactory.getLog(QuickStartJFrame.class);

	private static QuickStartJFrame qsJFrame;

	public static QuickStartJFrame getInstance() {
		synchronized (QuickStartJFrame.class) {
			if (qsJFrame == null) {
				qsJFrame = new QuickStartJFrame();
			}
		}
		return qsJFrame;
	}

	/** Creates new form QuickStartJFrame */
	private QuickStartJFrame() {
		initComponents();

		// NONE 无装饰（即去掉标题栏）
		// FRAME 普通窗口风格
		// PLAIN_DIALOG 简单对话框风格
		// INFORMATION_DIALOG 信息对话框风格
		// ERROR_DIALOG 错误对话框风格
		// COLOR_CHOOSER_DIALOG 拾色器对话框风格
		// FILE_CHOOSER_DIALOG 文件选择对话框风格
		// QUESTION_DIALOG 问题对话框风格
		// WARNING_DIALOG 警告对话框风格
		this.getRootPane().setWindowDecorationStyle(JRootPane.NONE);// 采用指定的窗口装饰风格

		// 定位窗口在屏幕的位置
		if (GlobalVar.CONFIG == null || GlobalVar.CONFIG.isEmpty()) {
			Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			Dimension frameSize = getSize();
			setLocation(new Point((screenSize.width - frameSize.width) / 2,
					(screenSize.height - frameSize.width) / 2));
		} else {
			Point point = DataUtil.getPointFromHashMap();
			// Dimension screenSize =
			// Toolkit.getDefaultToolkit().getScreenSize();
			// Dimension frameSize = getSize();
			setLocation(point);
		}
		// 设置底色
		this.getContentPane().setBackground(new Color(204, 204, 255));

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">
	private void initComponents() {

		autoTextField = new AutoCompletionField();
		jLabel1 = new JLabel();

		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setUndecorated(true);
		addWindowListener(new WindowAdapter() {
			public void windowDeactivated(WindowEvent evt) {
				formWindowDeactivated(evt);
			}
		});

		init();
		autoTextField.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent evt) {
				autoTextFieldKeyPressed(evt);
			}
		});

		jLabel1.setIcon(new ImageIcon(getClass().getResource(
				"/org/lifxue/jqda/ui/butterfly32.png")));

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(
				GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(autoTextField,
										GroupLayout.PREFERRED_SIZE, 431,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jLabel1)
								.addContainerGap(14, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout.createParallelGroup(
				GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								layout.createParallelGroup(
										GroupLayout.Alignment.BASELINE)
										.addComponent(autoTextField,
												GroupLayout.DEFAULT_SIZE, 34,
												Short.MAX_VALUE)
										.addComponent(jLabel1))
						.addContainerGap()));

		pack();
	}

	private void autoTextFieldKeyPressed(KeyEvent evt) {
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			String str = autoTextField.getText();
			if (Command.run(str)) {
				this.setVisible(false);
			}
		}
	}

	private void formWindowDeactivated(WindowEvent evt) {
		// frame失去焦点时，窗口隐藏
		this.setVisible(false);
	}

	private void init() {
		this.addMouseListener(moveWindowListener);
		this.addMouseMotionListener(moveWindowListener);
		updateData();

	}

	public void updateData() {
		List<String> tempvector = getDate();
		((AutoCompletionField) autoTextField)
				.setFilter(new DefaultCompletionFilter(tempvector));
	}

	// 窗口的拖拽移动
	private MouseAdapter moveWindowListener = new MouseAdapter() {

		private Point lastPoint = null;

		@Override
		public void mousePressed(MouseEvent e) {
			lastPoint = e.getLocationOnScreen();
		}

		@Override
		public void mouseDragged(MouseEvent e) {
			Point point = e.getLocationOnScreen();
			int offsetX = point.x - lastPoint.x;
			int offsetY = point.y - lastPoint.y;
			Rectangle bounds = QuickStartJFrame.this.getBounds();
			bounds.x += offsetX;
			bounds.y += offsetY;
			QuickStartJFrame.this.setBounds(bounds);
			lastPoint = point;
			// logger.debug(point.x +":"+point.y);
			GlobalVar.CONFIG.put(GlobalConstant.CONFIG_FILE_X,
					String.valueOf(QuickStartJFrame.this.getBounds().x));
			GlobalVar.CONFIG.put(GlobalConstant.CONFIG_FILE_Y,
					String.valueOf(QuickStartJFrame.this.getBounds().y));
			// logger.debug("x="+GlobalVar.CONFIG_HM.get(GlobalConstant.CONFIG_FILE_X);
			// logger.debug("y="+GlobalVar.CONFIG_HM.get(GlobalConstant.CONFIG_FILE_Y);
		}
	};

	/**
	 * 得到数据
	 * 
	 * @return
	 */
	public List<String> getDate() {
		List<AppInfoBean> list = new ArrayList<AppInfoBean>();
		Iterator<Entry<String, List<AppInfoBean>>> i = GlobalVar.APPLICATIONS
				.entrySet().iterator();
		while (i.hasNext()) {
			Entry<String, List<AppInfoBean>> entry = (Entry<String, List<AppInfoBean>>) i
					.next();
			String key = (String) entry.getKey(); // 返回与此项对应的键
			List<AppInfoBean> pathlist = (List<AppInfoBean>) entry.getValue(); // 返回与此项对应的值
			for (AppInfoBean value : pathlist) {
				AppInfoBean tempApp = new AppInfoBean();
				tempApp.setVolumeOfUse(value.getVolumeOfUse());
				tempApp.setPath(key + GlobalConstant.QSFRAME_DELIMITER
						+ value.getPath());
				list.add(tempApp);
			}
		}

		// Collections.sort(list);//排序
		Collections.sort(list, Collections.reverseOrder());// 倒序
		List<String> temp = new ArrayList<String>();
		for (int inx = 0; inx < list.size(); inx++) {
			temp.add(list.get(inx).getPath());
		}

		return temp;
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				new QuickStartJFrame().setVisible(true);
			}
		});
	}

	private JTextField autoTextField;
	private JLabel jLabel1;
}
